package pers.wk.producer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import pers.wk.rabbitmq.Constants;

import java.util.Map;

/**
 * 通过实现 ReturnCallback 接口，启动消息失败返回，比如路由不到队列时触发回调
 * 当消息不能被正确路由到某个queue时，会回调如下方法
 */
@Component
@Slf4j
public class ReturnCallback implements RabbitTemplate.ReturnCallback {

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        MessageProperties messageProperties = message.getMessageProperties();
        Map<String, Object> headers = messageProperties.getHeaders();
        String msgId = (String) headers.get(Constants.MSG_ID);
        String msg = new String(message.getBody());
        log.info(String.format("消息 【msgId：{%s}】【msg：{%s}】不能被正确路由，routingKey为 【{%s}】", msgId, msg, routingKey));
    }
}
